import service from '@/utils/request'
import {updateTask} from "@/utils/tasknotify";

const path = '/datasource'

const _ExecQueryQueue = [] //查询队列
let _ExecQueryQueuing = false  //正在执行中


/**
 * 获取数据源列表
 * @param data
 * @returns {Promise<AxiosResponse<any>>}
 */
export function getList(data) {
  return new Promise((resolve, reject) => {
    service.get(path + "/getList", {
      params: data
    }).then(resp => {
      resp.data.records.forEach(t => {
        t = resolveObj(t)
      })
      resolve(resp.data)
    }).catch(error => {
      reject(error)
    })
  })

}

/**
 * 获取单个数据源对象
 * @param id
 * @returns {Promise<AxiosResponse<any>>}
 */
export function getDataSource(id) {
  return new Promise((resolve, reject) => {
    service.get(path + "/" + id).then(resp => {
      let dataSource = resp.data
      resolve(resolveObj(dataSource))
    }).catch(error => {
      reject(error)
    })
  })
}

function resolveObj(dataSource) {
  if (typeof dataSource.preDataFields == 'string') {
    dataSource.preDataFields = JSON.parse(dataSource.preDataFields)
  }
  if (typeof dataSource.chooseTables == 'string') {
    dataSource.chooseTables = JSON.parse(dataSource.chooseTables)
  }
  if (typeof dataSource.tableRelations == 'string') {
    dataSource.tableRelations = JSON.parse(dataSource.tableRelations)
  }
  return dataSource
}

/**
 * 删除数据源
 * @param id
 * @returns {Promise<AxiosResponse<any>>}
 */
export function del(id) {
  return service.delete(path + "/" + id)
}

/**
 * 保存数据源
 * @param data
 * @returns {Promise<AxiosResponse<any>>}
 */
export function saveDataSource(data) {
  const obj = Object.assign({}, data)
  obj.tableRelations = '[]'
  obj.chooseTables = '[]'
  obj.preDataFields = JSON.stringify(obj.preDataFields)
  obj.queryType = 1
  return service.post(path, obj)
}

/**
 * 获取查询结果
 * @param request 请求参数
 * @param callback 回调函数
 * @param directExec  直接执行或加入队列中执行
 */
export function getDataQuery(request, callback, directExec) {
  const task = updateTask({
    msg: request.Comments,
    show: request.showLoading
  });
  const queue = {
    callback: callback,
    task: task,
    request: request
  }
  if (directExec) {
    execQueryQueue(queue, false);
  } else {
    _ExecQueryQueue.push(queue);
    if (!_ExecQueryQueuing) {
      todoQueryQueue();
    }
  }
}

function todoQueryQueue() {
  const queue = _ExecQueryQueue.shift();
  if (queue) {
    _ExecQueryQueuing = true;
    execQueryQueue(queue, true);
  } else {
    _ExecQueryQueuing = false;
  }
}

/**
 * 执行查询
 * @param queue 查询队列
 * @param isContinue 是否继续
 */
function execQueryQueue(queue, isContinue) {
  service.post(path + "/Query3", queue.request, {timeout: -1}).then(resp => {
    queue.task.status = "success";
    if (queue.task.msg) {
      queue.task.msg = "【完成】" + queue.task.msg;
    }
    updateTask(queue.task);
    if (queue.callback) {
      //同环比处理
      if (queue.request.isYoy && resp.data.records[0]) {
        resp.data.records.forEach(d => {
          if (d.YoYValue) {
            d.YoYValue = Number(d.YoYValue);
          }
          if (d.YoYRate) {
            d.YoYRate = Number(d.YoYRate);
          }
          if (d.QoQValue) {
            d.QoQValue = Number(d.QoQValue);
          }
          if (d.QoQRate) {
            d.QoQRate = Number(d.QoQRate);
          }
        });

        //日期排序
        let dateField = queue.request.fields.find(d => {
          return d.slaveType === 0 && d.dataType === 4;
        });
        if (dateField) {
          resp.data.records.sort((a, b) => {
            return a[dateField.name] - b[dateField.name];
          });
        }
      }

      try {
        queue.callback(resp.data.records);
      } catch (err) {
        console.error(err);
      }
    }
    if (isContinue) {
      todoQueryQueue();
    }
  }).catch(error => {
    queue.task.status = "error";
    if (queue.task.msg) {
      queue.task.msg = "【出错】" + queue.task.msg + ":" + error;
    }
    updateTask(queue.task);
    todoQueryQueue();
  })
}

